package com.neusoft.neuiotms.dcom.converter.alter;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.neusoft.bizcore.web.dto.AbstractConverter;
import com.neusoft.neuiotms.dcom.dto.alter.AlterCustomerReviewDTO;
import com.neusoft.neuiotms.dcom.model.alter.AlterCustomerReview;
import com.neusoft.neuiotms.dcom.model.alter.AlterCustomerReviewAnnex;
import com.neusoft.neuiotms.dcom.repository.alter.AlterCustomerReviewAnnexRepository;
import com.neusoft.neuiotms.dcom.repository.alter.AlterCustomerReviewRepository;

@Component
public class AlterCustomerReviewConverter
        extends AbstractConverter<AlterCustomerReview, AlterCustomerReviewDTO> {

    @Autowired
    private AlterCustomerReviewRepository customerReviewRepository;
    @Autowired
    private AlterCustomerReviewAnnexRepository customerReviewAnnexRepository;
    @Autowired
    private AlterCustomerReviewAnnexConverter customerReviewAnnexConverter;

    @Override
    public AlterCustomerReview toModel(final AlterCustomerReviewDTO dto) {

        AlterCustomerReview model;
        if (dto.isNew()) {
            model = new AlterCustomerReview();
        } else {
            model = this.customerReviewRepository.getOne(dto.getId());
        }

        model.setTaskId(dto.getTaskId());
        model.setWorkNum(dto.getWorkNum());
        model.setSatisfaction(dto.getSatisfaction());

        final List<AlterCustomerReviewAnnex> annexs = model.getAnnex().stream().collect(Collectors.toList());

        annexs.forEach(k -> {
            model.getAnnex().remove(k);
            this.customerReviewAnnexRepository.delete(k);
        });

        dto.getAnnex().stream().map(s -> {
            final AlterCustomerReviewAnnex annex = this.customerReviewAnnexConverter.toModel(s);
            annex.setCustomerReview(model);
            return annex;
        }).forEach(model.getAnnex()::add);

        return model;
    }

    @Override
    public AlterCustomerReviewDTO toDTO(final AlterCustomerReview model, final boolean forListView) {

        final AlterCustomerReviewDTO dto = new AlterCustomerReviewDTO();
        dto.setId(model.getId());
        dto.setTaskId(model.getTaskId());
        dto.setWorkNum(model.getWorkNum());
        dto.setSatisfaction(model.getSatisfaction());

        model.getAnnex().stream().map(s -> this.customerReviewAnnexConverter.toDTO(s)).filter(k -> null != k)
                .forEach(dto.getAnnex()::add);
        return dto;
    }

}
